// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const _data = JSON.parse(JSON.stringify(event))
  const user = cloud.database().collection('users').where({
    _id: parseInt(_data._id)
  })
  const { data } = await user.get()
  data[0].comments[_data.index] = _data.comment
  delete data[0]._id
  const result = {}
  result.result1 = await user.update({
    data: data[0]
  })
  const comment = cloud.database().collection('comments').where({
    commentId: _data.comment.commentId
  })
  result.result2 = await comment.update({
    data: _data.comment
  })
  // 更改 books 中的数据
  const commentData = await comment.get()
  const bookId = commentData.data[0].bookId
  const booksDb = cloud.database().collection('books')
  const bookData = await booksDb.where({
    bookId
  }).get()
  const book = bookData.data[0]
  delete book._id
  book.comments.forEach(item => {
    if (item.commentId === _data.comment.commentId) {
      item.content = _data.comment.content
    }
  })
  result.result3 = await booksDb.where({
    bookId
  }).update({
    data: book
  })
  return result
}